<!--
 * @Author: actor
 * @Date: 2023-11-15 18:28:59
 * @email: 395593455@qq.com
 * @LastEditors: actor
 * @LastEditTime: 2023-12-20 13:31:53
 * @FilePath: \i-hos-app\shared\emr\src\views\tmpl\Tmpl.vue
 * @Description: 电子病历知识库
-->
<template>
  <transition name="slide" mode="out-in">
    <div class="tmpl" v-if="!isTmplEditVisible">
      <!-- 左侧菜单栏目 -->
      <TreeList :data="state" @updateCategory="getUpdateCategory" />

      <!-- 右侧主体内容 -->
      <Main class="tmpl_main">
        <TmplMain @updateDocTempJson="getUpdateDocTempJson" />
      </Main>
    </div>
    <TmplEdit v-else :docTempJson="docTempJson" @back="updateBack"></TmplEdit>
  </transition>
</template>

<script setup lang="ts">
  import { reactive, getCurrentInstance, watch, ref, Ref } from 'vue'
  import { useRoute, RouteMeta } from 'vue-router'

  // 自定义组件
  import TreeList from '../../components/common/treeList.vue'
  import TmplMain from './tmplMain.vue'
  import TmplEdit from './TmplEdit.vue'

  // 配置类型约束
  import { IPageShare, IStateSet } from '../../interface/pageShare'
  // 仓库数据以及解构store的配置数据
  import { useEmrPageShare } from '../../store/emrPageShare'
  const emrPageShare: IPageShare = useEmrPageShare()

  // 初始化配置
  let isTmplEditVisible: Ref<boolean> = ref(false), // 编辑模板
    docTempJson: Ref<any> = ref('') // 当前模板数据

  const { proxy } = getCurrentInstance() as any,
    route = useRoute(),
    state: IStateSet = reactive({
      type: '病历模板', // 树菜单标题
      isHandletree: false, // 是否可以动态新增编辑删除树菜单
      treeData: [], // 树菜单数据
      filterTreeData: [],
      treeDataDefaultProps: {
        // 树菜单默认绑定的字段
        children: 'childList',
        label: 'deptName',
        id: 'id',
      },
      dict: JSON.parse(window.sessionStorage.DictStore).baseDict.filter((item: any) => item.dictCode == 'FH0135'),
    })

  // 初始化获取知识库的分类
  const fetchOrganization = (flag?: String) => {
    const Url: String = APP_GLOBAL.API['EMR']['category-organization']
    proxy.$http.requestJSON('post', Url).then((res: any) => {
      if (!!res.data.length) {
        let treeData: any = [
          {
            deptName: '通用模板',
            childList: [],
            id: 1,
          },
          {
            deptName: '归属机构',
            childList: res.data,
            id: 2,
          },
        ]
        for (let obj of state.dict) {
          ;(obj.deptName = obj.dictItemName),
            (obj.childList = !!obj.childList ? obj.childList : null),
            treeData[0].childList.push(obj)
        }
        state.treeData = treeData
        setTimeout(() => {
          // 默认第一个分类为选中状态
          emrPageShare.$patch((state: IPageShare): void => {
            state.activetreeList = treeData[0]
            state.organTreeList = res.data
          })
          // 获取选中的表格的数据
          emrPageShare.fetchOrganizationTable(proxy)
        })
      }
    })
  }
  // fetchOrganization()

  const filterTree = (val: String, tree: any) => {
    let newArr: any = []
    if (!(tree.length && val)) {
      // 如果搜索关键字为空直接返回源数据
      return tree
    }
    for (let item of tree) {
      if (item.deptName.indexOf(val) > -1) {
        // 匹配到关键字的逻辑
        newArr.push(item) // 如果匹配到就在数值中添加记录
        continue // 匹配到了就退出循环了此时如果有子集也会一并带着
      }

      if (item.childList && item.childList.length) {
        // 如果父级节点没有匹配到就看看是否有子集，然后做递归
        let subArr: any = filterTree(val, item.childList) // 缓存递归后的子集数组
        if (subArr && subArr.length) {
          // 如果子集数据有匹配到的节点
          let node: any = { ...item, childList: subArr } // 关键逻辑，缓存父节点同时将递归后的子节点作为新值
          newArr.push(node) // 添加进数组
        }
      }
    }
    return newArr
  }

  // 通过关键字搜索更新树菜单
  const getUpdateCategory = (flag?: String) => {
    state.filterTreeData = []
    if (!!flag) {
      state.filterTreeData = filterTree(flag, state.treeData)
    } else {
      fetchOrganization(flag)
    }
  }

  // 更新模板数据
  const getUpdateDocTempJson = (bol: boolean, flag: string) => {
    isTmplEditVisible.value = bol
    docTempJson.value = flag
  }

  // 返回更细数据
  const updateBack = () => {
    isTmplEditVisible.value = false
    fetchOrganization()
  }

  // 监听路由变化，重新获取分类数据
  watch(
    (): any => route.meta,
    (newValue: RouteMeta): any => {
      emrPageShare.$patch((state: IPageShare): void => {
        state.tableList = []
      })
      if (newValue.title == '病历模板') fetchOrganization()
    },
    { immediate: true }
  )
</script>

<style lang="scss" scoped>
  .tmpl {
    width: 100%;
    height: 100%;
    padding: 5px;
    display: flex;
    &_main {
      flex: 1;
      height: 100%;
      padding: 0;
    }
  }
  :deep(.el-dialog__header) {
    margin-right: 0;
    .el-dialog__title {
      font-size: 14px;
    }
  }
  :deep(.el-dialog__body) {
    padding-top: 15px;
    padding-bottom: 15px;
  }
  .slide-enter-from {
    opacity: 0;
    // transform: translateX(100px);
  }
  .slide-enter-to {
    opacity: 1;
    // transform: translateX(0);
  }
  .slide-enter-active {
    transition: 0.2s;
  }

  .slide-leave-from {
    opacity: 1;
    // transform: translateX(0);
  }
  .slide-leave-to {
    opacity: 0;
    // transform: translateX(100px);
  }
  .slide-leave-active {
    transition: 0.2s;
  }
</style>
